package com.dounine.clouddisk360.parser;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dounine.clouddisk360.exception.CloudDiskException;
import com.dounine.clouddisk360.parser.deserializer.BaseConst;
import com.dounine.clouddisk360.parser.deserializer.MsgConst;
import com.dounine.clouddisk360.parser.deserializer.user.size.UserSize;
import com.dounine.clouddisk360.parser.deserializer.user.size.UserSizeConfig;
import com.dounine.clouddisk360.parser.deserializer.user.size.UserSizeConst;
import com.dounine.clouddisk360.parser.deserializer.user.size.UserSizeRequestInterceptor;
import com.dounine.clouddisk360.parser.deserializer.user.size.UserSizeResponseHandle;
import com.dounine.clouddisk360.parser.deserializer.user.token.UserTokenRequestInterceptor;
import com.dounine.clouddisk360.pool.PoolingHttpClientConnection;
import com.dounine.clouddisk360.util.TimeUtil;

public class UserSizeParser extends BaseParser<UserSizeConfig> {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserSizeParser.class);
	
	public static final String GET_SIZE_APTH = "/user/getsize/?ajax=1";

	@Override
	public void initConfig(UserSizeConfig userSizeConfig) {
		
		super.initConfig(userSizeConfig);//必需调用父类的initConfig方法,或者重写里面所定义的cookieStore路径
	}

	public UserSize parse() {
		HttpGet request = initRequest(super.config);;
		UserSize userSize = execute(request);
		
		super.setBianaryFilename("userSize.txt");
		super.setBianaryPath(config.getBasePath()+"user/");
		super.writeObjToDisk(userSize);
		
		return userSize;
	}

	public HttpGet initRequest(UserSizeConfig config) {
		try {
			String host = String.valueOf(httpClientContext.getAttribute(BaseConst.REQUEST_HOST_NAME));
			if(StringUtils.isBlank(host)){
				throw new CloudDiskException("主机地址不能为空");
			}
			URIBuilder uri = new URIBuilder();
			uri.setScheme(UserSizeConst.SCHEME_HTTP);
			uri.setHost(host);
			uri.setPath(GET_SIZE_APTH);
			uri.addParameter("t", TimeUtil.getTimeLenth(10));
			HttpGet request = new HttpGet(uri.build());
			return request;
		} catch (URISyntaxException e) {
			LOGGER.error("生成用户空间信息请求对象失败");
		}
		return null;
	}
	
	public UserSize execute(HttpGet request) {
		
		super.httpClient = HttpClients.custom()
				.setConnectionManager(PoolingHttpClientConnection.getInstalce())
				.addInterceptorLast(new UserSizeRequestInterceptor())
				.setDefaultRequestConfig(cookieRequestConfig())
				.build();
		try {
			return super.httpClient.execute(request,new UserSizeResponseHandle(this), super.httpClientContext);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
